import React, { ReactElement, useState, useEffect } from 'react';

// 引入 api
import { getGoodsType, updateGoodsType, updateTypes } from '@/api/goodsType';
import { message, TreeSelect, Form, Select } from 'antd';
const { Option } = Select;
import { SettingOutlined } from '@ant-design/icons';

import ProForm, {
  DrawerForm,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-form';
interface Props {
  reload: () => void;
  data: any;
}

export default function UpdateGoodsTypes({
  reload,
  data,
}: Props): ReactElement {
  //获取树形空间所需求的数据
  useEffect(() => {
    getData();
  }, []);

  const [treeData, setTreeData] = useState<any[]>([]);
  const getData = async () => {
    const res = await getGoodsType({});
    if (res.status == 200) {
      setTreeData([...res.data.rows.children]);
    }
  };

  // 修改 方法
  const UPDATE_GOODS_TYPE = async (values: any) => {
    const { parentId, status, title } = values;
    const obj = {
      id: data.id,
      status,
      name: title,
      pid: parentId,
    };
    const res = await updateGoodsType(obj);
    console.log(res);
    if (res.status === 200) {
      reload();
      message.success('修改成功');
      return true;
    } else {
      message.error('修改失败');
      return true;
    }
  };
  return (
    <DrawerForm
      title="新增类型"
      trigger={<SettingOutlined style={{ color: '#4A9FF5' }} />}
      width={500}
      initialValues={data}
      onFinish={async (values) => {
        const res = await UPDATE_GOODS_TYPE(values);
        return res;
      }}
    >
      <ProFormText
        label="商品类型名称："
        name="title"
        rules={[{ required: true, message: '请输入名称' }]}
      />
      <Form.Item
        label="商品类型状态"
        name="status"
        style={{ width: '328px' }}
        rules={[
          {
            required: true,
            message: '请选择角色!',
          },
        ]}
      >
        <Select allowClear>
          <Option value="1">启用</Option>
          <Option value="2">停用</Option>
        </Select>
      </Form.Item>
      <Form.Item label="上级商品类型：" name="parentId">
        <TreeSelect
          style={{ width: 400 }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          treeData={treeData}
          placeholder="Please select"
        />
      </Form.Item>
    </DrawerForm>
  );
}
